﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using Syncfusion.XForms.RichTextEditor;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using TabbedTemplate.Models;
using TabbedTemplate.Services;

namespace TabbedTemplate.ViewModels
{
    /// <summary>
    /// 查看打卡内容ViewModel
    /// </summary>
    public sealed class PunchViewPageViewModel : ViewModelBase,
        INotifyPropertyChanged
    {
        public new event PropertyChangedEventHandler PropertyChanged;
        public void RaisePropertyChange(
            [CallerMemberName] string propertyname = null)
        {
            PropertyChanged?.Invoke(this,
                new PropertyChangedEventArgs(propertyname));
        }





        public string _punchContent;

        public string PunchContent
        {
            get => _punchContent;
            set => Set(nameof(PunchContent), ref _punchContent, value);
        }

        public string _storeName;

        public string StoreName
        {
            get => _storeName;
            set => Set(nameof(StoreName), ref _storeName, value);
        }

        public bool _notEdit;

        public bool NotEdit
        {
            get => _notEdit;
            set => Set(nameof(NotEdit), ref _notEdit, value);
        }

        public bool _edit;

        public bool Edit
        {
            get => _edit;
            set => Set(nameof(Edit), ref _edit, value);
        }

        private PunchTimeStampParameter _punchTimeStampParameter;

        public PunchTimeStampParameter PunchTimeStampParameter
        {
            get => _punchTimeStampParameter;
            set =>
                Set(nameof(PunchTimeStampParameter),
                    ref _punchTimeStampParameter, value);
        }

        private string _punchIndex;

        public string PunchIndex
        {
            get => _punchIndex;
            set => Set(nameof(PunchIndex), ref _punchIndex, value);
        }

        private IList<byte[]> _images;

        public IList<byte[]> Images
        {
            get => _images;
            set => Set(nameof(Images), ref _images, value);
        }


        //绑定操作命令
        private string _action;

        public string Action
        {
            get => _action;
            set => Set(nameof(Action), ref _action, value);
        }

        public bool IsVisual { get; set; }
        private RelayCommand _pageAppearingCommand;

        public RelayCommand PageAppearingCommand =>
            _pageAppearingCommand ??= new RelayCommand(async () =>
                await PageAppearingCommandFunction());

        public async Task PageAppearingCommandFunction()
        {

            if (!_preferenceStorage.Get("PunchEdit", true))
            {
                return;
            }
            Action = "编辑";
            RaisePropertyChanged($"Action");
            NotEdit = true;
            Edit = false;
            RaisePropertyChange($"NotEdit");
            RaisePropertyChange($"Edit");
            ImageViewModelCollection.Clear();
            RaisePropertyChanged($"ImageViewModelCollection");
            PunchContent = PunchTimeStampParameter.PunchInfo.Content;
            RaisePropertyChange($"PunchContent");
            //获取Images
            Images =
                await _imageService.ReadImageAsync(PunchTimeStampParameter
                    .PunchInfo.Timestamp);
            RaisePropertyChange($"Images");
            IsVisual = Images.Count != 0;
            RaisePropertyChange($"IsVisual");
            //初始化ImageViewModelCollection
            var models = new List<ImageViewModel>();
            foreach (var Image in Images)
            {
                ImageSource = Image;
                models.Add(new ImageViewModel(null, this));
            }
            ImageSource = null;
            foreach (var imageViewModel in models)
            {
                ImageViewModelCollection.Add(imageViewModel);
            }

            RaisePropertyChange($"ImageViewModelCollection");
            _preferenceStorage.Set("PunchEdit", false);
        }

        private RelayCommand _editCommand;

        public RelayCommand EditCommand =>
            _editCommand ??=
                new RelayCommand(async () => await EditCommandFunction());

        public async Task EditCommandFunction()
        {
            if (Action == "编辑")
            {
                Edit = true;
                NotEdit = false;
                Action = "保存";
            }
            else
            {
                Edit = false;
                NotEdit = true;
                Action = "编辑";
                //更新PunchInfo的时间戳，内容，图片。
                _imageService.DeleteFolder(PunchTimeStampParameter.PunchInfo.Timestamp);
                var longToReturn = DateTime.Now.Ticks;
                PunchTimeStampParameter.PunchInfo.Timestamp = longToReturn;
                PunchTimeStampParameter.PunchInfo.Content = PunchContent;
                await _punchInfoStorage.SavePunchInfoAsync(PunchTimeStampParameter.PunchInfo, false);
                //先建文件夹
                _imageService.CreateFolder(longToReturn);
                for (var i = 0; i < ImageViewModelCollection.Count; i++)
                {
                    await _imageService.SaveImageAsync(longToReturn,
                        ImageViewModelCollection[i].ImageSource1, longToReturn + "-" + i + ".png");
                }


            }

            RaisePropertyChange($"Action");
            RaisePropertyChange($"Edit");
            RaisePropertyChange($"NotEdit");
        }

        private RelayCommand _viewStoreCommand;

        public RelayCommand ViewStoreCommand =>
            _viewStoreCommand ??= new RelayCommand(async () =>
                await ViewStoreCommandFunction());

        public async Task ViewStoreCommandFunction()
        {
            var temp = PunchTimeStampParameter.Store;
            await _punchNavigationService.NavigateToStorePunchesPage(temp);
        }


        // ******** 图片相关处理
        public async Task AddImageViewModel(ImageViewModel imageViewModel)
        {
            _preferenceStorage.Set("newPunch", false);
            int index = ImageViewModelCollection.IndexOf(imageViewModel);
            int count = ImageViewModelCollection.Count;
            if (imageViewModel.ImageSource1 == null)
            {
                var res = await _alertService.ShowAlert("请选择一种方式", "取消", null,
                    "拍照", "从本地相册选取一张照片", null);
                switch (res)
                {
                    case "拍照": _imageSource = await _pickPhotoService.TakePhotoAsync(); break;
                    case "从本地相册选取一张照片": _imageSource = await _pickPhotoService.PickPhotoAsync(); break;
                }
                if (_imageSource == null)
                {
                    return;
                }
            }
            else
            {
                return;
            }

            //TODO SAVE
            ImageViewModelCollection.Add(new ImageViewModel(null, this));
            IsVisual = true;
            RaisePropertyChange($"IsVisual");
            RaisePropertyChange($"ImageViewModelCollection");
        }

        public void RemoveImageViewModel(ImageViewModel imageViewModel)
        {
            _preferenceStorage.Set("newPunch", false);
            ImageViewModelCollection.Remove(imageViewModel);
            if (ImageViewModelCollection.Count != 0)
                return;
            IsVisual = false;
            RaisePropertyChange($"IsVisual");
        }

        public byte[] ImageSource
        {
            get => _imageSource;
            set => Set(nameof(ImageSource), ref _imageSource, value);
        }

        private byte[] _imageSource;

        /// <summary>
        /// ImageViewModel容器。
        /// </summary>
        private ObservableCollection<ImageViewModel> _imageViewModelCollection;
        public ObservableCollection<ImageViewModel> ImageViewModelCollection
        {
            get => _imageViewModelCollection;
            set =>
                Set(nameof(ImageViewModelCollection),
                    ref _imageViewModelCollection, value);
        }

        private ObservableCollection<object> _toolBarItems;

        public ObservableCollection<object> ToolBarItems
        {
            get => _toolBarItems;
            set => Set(nameof(ToolBarItems), ref _toolBarItems, value);
        }
        // ******** 构造函数

        private readonly IPreferenceStorage _preferenceStorage;
        private readonly IImageService _imageService;
        private readonly IPickPhotoService _pickPhotoService;
        private readonly IPunchInfoStorage _punchInfoStorage;
        private readonly IAlertService _alertService;
        private readonly IPunchNavigationService _punchNavigationService;

        public PunchViewPageViewModel(IPreferenceStorage preferenceStorage,
            IImageService imageService, IPickPhotoService pickPhotoService, IPunchInfoStorage punchInfoStorage, IAlertService alertService, IPunchNavigationService punchNavigationService)
        {
            ImageViewModelCollection =
                new ObservableCollection<ImageViewModel>();
            ToolBarItems = new ObservableCollection<object>();
            ToolBarItems.Add(ToolbarOptions.Bold);
            ToolBarItems.Add(ToolbarOptions.Italic);
            ToolBarItems.Add(ToolbarOptions.Underline);
            ToolBarItems.Add(ToolbarOptions.FontColor);
            ToolBarItems.Add(ToolbarOptions.HighlightColor);
            ToolBarItems.Add(ToolbarOptions.FontSize);
            ToolBarItems.Add(ToolbarOptions.ParagraphFormat);
            ToolBarItems.Add(ToolbarOptions.BulletList);
            ToolBarItems.Add(ToolbarOptions.NumberList);
            ToolBarItems.Add(ToolbarOptions.Alignment);
            ToolBarItems.Add(ToolbarOptions.IncreaseIndent);
            ToolBarItems.Add(ToolbarOptions.DecreaseIndent);
            ToolBarItems.Add(ToolbarOptions.Hyperlink);
            ToolBarItems.Add(ToolbarOptions.ClearFormat);
            RaisePropertyChange($"ToolBarItems");
            Images = new List<byte[]>();
            Action = "编辑";
            StoreName = "查看店铺";
            RaisePropertyChange($"StoreName");
            RaisePropertyChange($"Images");
            RaisePropertyChanged($"Action");

            _imageService = imageService;
            _preferenceStorage = preferenceStorage;
            _pickPhotoService = pickPhotoService;
            _punchInfoStorage = punchInfoStorage;
            _alertService = alertService;
            _punchNavigationService = punchNavigationService;
        }
    }
}
